package com.gzh.system.service.timetask;

import com.google.common.collect.Lists;
import com.gzh.core.dao.mapper.WorkMapper;
import com.gzh.core.dao.po.WorkEntity;
import com.gzh.core.util.NumericHelper;
import com.gzh.core.util.StringUtils;
import com.gzh.system.dao.mapper.CommonMapper;
import com.gzh.system.dao.po.QueryRemindUserEntity;
import com.gzh.system.service.MailService;
import com.sun.org.apache.bcel.internal.generic.I2F;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Condition;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author guanzh
 * @Date 2021/12/2 15:50
 * @Description
 */
@Component
@Slf4j
public class AutoRemindWorkTask {
    @Autowired
    private WorkMapper workMapper;
    @Autowired
    private CommonMapper commonMapper;
    @Autowired
    private MailService mailService;

    //作业截至提醒
    @XxlJob(value = "autoRemindWorkTask")
    public ReturnT<String> autoRemindWorkTask(String param) {
        try {
            log.info("调用作业截至提醒定时任务开始");
            Integer date = NumericHelper.toInteger(StringUtils.formatDate());
            WorkEntity workEntityQuery = new WorkEntity();
            workEntityQuery.setIsEnd(0);
            workEntityQuery.setIsPublish(1);
            List<WorkEntity> workEntityList = workMapper.select(workEntityQuery);
            if (!CollectionUtils.isEmpty(workEntityList)){
                List<Integer> workIdList = Lists.newArrayList();
                for (WorkEntity workEntity : workEntityList) {
                    Integer endDate = workEntity.getEndDate();
                    Integer differDays = StringUtils.getDifferDays(date, endDate);
                    if (differDays <= 1 && differDays != -1){
                        workIdList.add(workEntity.getWorkId());
                    }
                }
                if (!CollectionUtils.isEmpty(workIdList)){
                    List<QueryRemindUserEntity> list = commonMapper.queryRemindUser(workIdList);
                    if (!CollectionUtils.isEmpty(list)){
                        Map<Integer, List<QueryRemindUserEntity>> listMap = list.stream().collect(Collectors.groupingBy(t -> t.getUserId()));
                        for (Map.Entry<Integer, List<QueryRemindUserEntity>> listEntry : listMap.entrySet()) {
                            List<QueryRemindUserEntity> value = listEntry.getValue();
                            mailService.sendXXLMail(value);
                        }
                    }
                }
            }
            log.info("调用作业截至提醒定时任务结束");
        } catch (Exception e) {
            log.error("调用定时任务错误：作业截至提醒", e);
            return ReturnT.FAIL;
        }
        return ReturnT.SUCCESS;
    }


}
